import django_redis
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.generic.base import View
import  random,string
from captcha.image import ImageCaptcha
from django_redis import client
import logging
from mangguo_pro.utils .sms3 import send_sms_code


logger=logging.getLogger('django')


class Imagecode(View):
    def get(self,request,uuid):

        #随机生成验证码(四位数字）
        a=random.randint(1000,9999)
        b=str(a)

        # seed=string.digits  #生成0-9的字符串 '0123456789'
        # codelist=random.choice(seed,k=4)  #生成含有字符串的列表   ['2','6','8']
        # codestr=''.join(codelist)    #生成字符串 '7856'




        #根据生成的数字产生图片资源
        G_img=ImageCaptcha()
        imgcode=G_img.generate(chars=b)





        #保存到redis数据库
        redis_connect= django_redis.get_redis_connection('verify_code')
        redis_connect.setex(name='img_%s'%uuid,time=300,value=b)



       # 返回资源给前端
        return HttpResponse(imgcode,content_type='image/png')



class SMScodes(View):
    def get(self,request,phone):

         #比对并删除图片验证码

         #发送短信验证码

         #获取请求参数
         img_client=request.GET.get('imgcode','')
         uuid=request.GET.get('uuid','')
         print('img_client',img_client)
         uuid = uuid.replace('/','')
         print("uuid",uuid)

         #校验请求参数(完整性判断)
         if not all([img_client,uuid,phone]):
             return JsonResponse({'code':'4001','errormsg':'缺少必传参数'})



         #获取服务器生成的图片验证码

         redis_conn= django_redis.get_redis_connection('verify_code')
         img_server=redis_conn.get('img_%s'%uuid)


         #进行匹配(非空判断，一致性判断)
         if img_server is None:
             return JsonResponse({'code':'4002','errormsg':'图片验证码为空'})

         if img_client.lower()!=img_server.decode('utf-8').lower():
             return JsonResponse({'code':'4003','errormsg':'图片验证码不一致'})



         # 删除图片验证码
         try:
             redis_conn.delete('img_%s'%uuid)

         except Exception as e:
             logger.error(e)

         #生成短信验证码
         rd_server=random.randint(100000,999999)
         print("短信验证码为:",rd_server)
         generate_sms=str(rd_server)
         redis_conn.setex('sms_%s'%phone,60,generate_sms)
         redis_conn.setex('is_send_%s'%phone,60,1)



         #异步执行发送短信验证码

         from mangguo_pro.celery_tasks.sms.tasks import  huyi_send_sms_code

         #celery 异步发送短信验证码

         ret=huyi_send_sms_code.delay(phone,generate_sms)

         if ret:
             return JsonResponse({'code':200,'errormsg':'OK'})

         return  JsonResponse({'code':5001,'errormsg':'发送短信验证码错误'})



         #发送短信验证码
         # ret= send_sms_code(generate_sms,phone)
         # print(ret)



         #根据生成的参数响应给前端
         # if ret.get('code')==2:
         #    return JsonResponse({'code':'200','errormsg':'OK'})
         # return JsonResponse({'code':'5001','errormsg':'发送短信验证码失败'})
         # print(JsonResponse)


class Checksmscode(View):
    def get(self,request,phone):
        #接受请求参数
        smscode_client=request.GET.get('smscode','')

        #校验请求参数(判断完整性）
        if not all(['phone','smscode']):
            return JsonResponse({'code':4001,'errormsg':'请求参数不完整'})

        #连接redis数据库 ，进行查询比对
        redis_conn= django_redis.get_redis_connection('verify_code')
        is_send=redis_conn.get('is_send_%s'%phone)
        if  is_send:
            return  JsonResponse({'code':4004,'errormsg':'请不要重复发送验证码'})
        redis_server=redis_conn.get('sms_%s'%phone)
        if redis_server is None:
            return JsonResponse({'code': 4002,'errormsg':'验证码不存在'})
        redis_server=redis_server.decode('utf-8')
        if smscode_client!=redis_server:
            return JsonResponse({'code':4003,'errormsg':'输入的验证码不正确'})

        #返回响应给前端
        return JsonResponse({'code': 200,'errormsg':'OK'})
